#ifndef IR_H
#define IR_H

#include "WConstants.h"
//#include "WProgram.h"
// NEC protocol time constants
#define NEC_BIT_START      4000 //!< Starting bit timeout
#define NEC_BIT_0          1400	//!< Code for binary 0
#define NEC_BIT_1           420 //!< Code for binary 1
#define NEC_START_TIMEOUT 10000 //!< Start timeout
#define NEC_BIT_TIMEOUT    3000 //!< bit timeout
#define NEC_REPEAT_S      20000 //!< Repeat timeot
#define NEC_REPEAT_TIMEOUT_S 70000	//!< Repeat timeout s
#define NEC_REPEAT         2000		//!< Repeat
#define NEC_REPEAT_TIMEOUT 110000	//!< Repeat timeout2

extern byte pulseport;

/** Start reading from the specified buffer-type port
*/
void processIR(){
  int bitStart, bitTime, bitValue;
  int in;
  int vpn=0;
  byte codeIR[4] = {0, 0, 0, 0}; ///< Code captured by a buffer port

  // Interrupt deactivated
  if (pulseport==2) in=0;
  if (pulseport==3) in=1;
  detachInterrupt(in);


  bitStart=pulseIn(pulseport, HIGH, NEC_START_TIMEOUT);
  if(bitStart > NEC_BIT_START){
    // Reading 4 bytes
    int i, j;
    for(i=0; i<4; i++){
      for(j=0; j<8; j++){
        bitTime=pulseIn(pulseport, HIGH, NEC_BIT_TIMEOUT);
        if(bitTime > NEC_BIT_1 && bitTime < NEC_BIT_0){
          // It's a 1
          bitSet(codeIR[i], j);
        }
        else{
        	 // It's a 0
          bitClear(codeIR[i], j);
        }
      }
    }

	/*
    //Formatting information:
    Serial.print("N: pulse ");
    for(i=0; i<4; i++){
      if(codeIR[i] < 0x10){
        Serial.print("0");
        Serial.print(codeIR[i], HEX);
      }
      else{
        Serial.print(codeIR[i], HEX);
      }
    }
    Serial.println(); */

    //! @todo format code here
	//FOREACHVPORT(i){
           //if ((vports[i][0]=='P') && (vports[i][1]==codeIR[0]) && \
           //(vports[i][2]==codeIR[1]) && (vports[i][3]==codeIR[2]) && \
           //(vports[i][4]==codeIR[3]))
           //{
           //     vpn = i+PINCOUNT;
           //}
	//}

    //if(vpn!=0) triggerPortChange(vpn,LOW,HIGH);
    // Verify if the pulse is repeating
    bitStart=pulseIn(pulseport, HIGH, NEC_REPEAT_TIMEOUT_S);
    if(bitStart > NEC_REPEAT){
      //Serial.println("N:repeat");
      // Verify again
      while(pulseIn(pulseport, HIGH, NEC_REPEAT_TIMEOUT) > NEC_REPEAT){
        //Serial.println("N:repeat");
      }
    }
  }
  //if(vpn!=0) triggerPortChange(vpn,HIGH,LOW);
  // Re-activate interrupt
  attachInterrupt(in, processIR, CHANGE);

}
#endif
